package com.ckf.login_wx.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import lombok.val;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckf.login_wx.entity.Bill;
import com.ckf.login_wx.entity.Odd;
import com.ckf.login_wx.entity.Repertory;
import com.ckf.login_wx.entity.RepertoryNum;
import com.ckf.login_wx.entity.RepertoryXH;
import com.ckf.login_wx.entity.Sell;
import com.ckf.login_wx.entity.Xinsell;
import com.ckf.login_wx.servic.BillService;
import com.ckf.login_wx.servic.OddService;
import com.ckf.login_wx.servic.RepertoryNumService;
import com.ckf.login_wx.servic.RepertoryService;
import com.ckf.login_wx.servic.RepertoryXHService;
import com.ckf.login_wx.servic.SellService;
import com.ckf.login_wx.servic.XinsellService;
import com.ckf.login_wx.util.Getpo;
import com.ckf.login_wx.util.Idname;
import com.github.pagehelper.PageHelper;

@RestController
public class Sellcontroller {
	@Autowired
    private XinsellService XinsellService;
	@Autowired
    private OddService OddService;
	@Autowired
    private BillService billService;
	@Autowired
    private RepertoryService repertoryService;
	@Autowired
    private RepertoryNumService repertoryNumService;
	@Autowired
    private RepertoryXHService repertoryXHService;
	@RequestMapping("/seleoddbycid")
    public boolean seleoddbycid(int odd){
		if(OddService.list((QueryWrapper<Odd>)Getpo.one("odd", odd)).size()==0){
			return true;
		}else
		return false;
	}
	@GetMapping("/addxinsell")
    public String addxinsell(String[] b,String odd,String name2,String phone,String anq,String time,String time2,String site,String saisie,String tupian,String total,String moneytotal,String faf) throws ParseException{
		int oddint=Integer.parseInt(odd);
		if(!seleoddbycid(oddint)&&faf.equals("add"))return "单号已存在！";
		if(Integer.parseInt(moneytotal)>Integer.parseInt(total)){
			return "实收货款大于应收货款！";
		}
		//处理小程序字符串返回问题
		for (int i = 0; i < b.length; i++) {
			if(b[i].indexOf('"')!=-1){
				b[i]=b[i].replace("\"", "");
			}
			if(b[i].indexOf('[')!=-1){
				b[i]=b[i].replace("[", "");
			}
		}
		//再次检查库存
		Map<String, Integer> maptotal = new HashMap<>();
		for (int n = 0; n < b.length; n++) {
			if(b[1+(n*6)].equals("")||b[1+(n*6)]==null)break;
			if(!maptotal.containsKey(b[1+(n*6)])){
				maptotal.put(b[1+(n*6)], Integer.parseInt((b[2+(n*6)])));
			}
			else{
				int z=maptotal.get(b[1+(n*6)]);
				maptotal.remove(b[1+(n*6)]);
				maptotal.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)])+z);
			}
		}
		for (String string : maptotal.keySet()) {
			if(maptotal.get(string)>repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", string)).get(0).getNum()){
				return "库存型号不足:"+string;
			}
		}
		//修改是直接删掉再添加
		if(faf.equals("up")){
			//存型号和数量
			Map<String, Integer> mapre = new HashMap<>();
			List<Xinsell> sellre =XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", odd));
			if(!XinsellService.remove(new QueryWrapper<Xinsell>().eq("odd", odd))||!OddService.remove(new QueryWrapper<Odd>().eq("odd", odd)))return "修改失败";
			//统计到mapre
			for (int i = 0; i < sellre.size(); i++) {
				if(!mapre.containsKey(sellre.get(i).getModele())){
					mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite());
				}else{
					int numre=mapre.get(sellre.get(i).getModele());
					mapre.remove(sellre.get(i).getModele());
					mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite()+numre);
				}
			}
			for (String s : mapre.keySet()) {
				RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
				RepertoryNum.setNum(RepertoryNum.getNum()+mapre.get(s));
				repertoryNumService.updateById(RepertoryNum);
			}
		}
		String uuid=""+UUID.randomUUID();
		uuid=uuid.substring(0,8);
		int count=0,sum=0;double total2=0;
		boolean f=false;
		//存型号和数量
		Map<String, Integer> map = new HashMap<>();
		Xinsell sell=new Xinsell();
		for (int n = 0; n < b.length; n++) {
			sell.setName(b[0+(n*6)]);
			sell.setModele(b[1+(n*6)]);
			sell.setUnite(b[3+(n*6)]);
			System.out.println(sell.returnstu());
			if(sell.returnstu()==""||sell.returnstu().length()==0)break;
			count++;
			sell.setQuantite(Integer.parseInt(b[2+(n*6)]));
			sell.setMoney(Double.parseDouble(b[4+(n*6)]));
			//sum+=Integer.parseInt(b[4+(n*6)]);
			sell.setOdd(oddint);
			sell.setCid(uuid);
			sell.setTotal(Double.parseDouble(b[5+(n*6)]));
			sell.setStatus(1);
			f=XinsellService.save(sell);
			total2+=sell.getTotal();
			int ii=0;
			if(map.containsKey(b[1+(n*6)])){
				ii=map.get(b[1+(n*6)]);
				map.remove(b[1+(n*6)]);
				map.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)])+ii);
			}else
			map.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)]));
		}
		if(!f)return "失败";
		//库存统计数量返还
		for (String s : map.keySet()) {
				RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
				RepertoryNum.setNum(RepertoryNum.getNum()-map.get(s));
				repertoryNumService.updateById(RepertoryNum);
		}
		
		Odd oddEntity =new Odd();
		oddEntity.setCid(uuid);
		oddEntity.setOdd(oddint);
		oddEntity.setCount(count);
		oddEntity.setName2(name2);
		oddEntity.setPhone(phone);
		oddEntity.setSaisie(saisie);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        oddEntity.setTime(simpleDateFormat.parse(time));
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        oddEntity.setTime2(simpleDateFormat2.parse(time2));
		oddEntity.setTupian(tupian);
		oddEntity.setTotal(total2);
		oddEntity.setDebt(total2-Double.parseDouble(moneytotal));
		oddEntity.setSite(site);
		oddEntity.setAnq(anq);
		oddEntity.setMoneytotal(Double.parseDouble(moneytotal));
		oddEntity.setStatus(1);
		oddEntity.setPrintstatus(0);
		//oddEntity.setTotal(sum);
		if(faf.equals("add")&&Double.parseDouble(moneytotal)!=0.00){
			Bill bill=new Bill();
	        bill.setMoney(Double.parseDouble(moneytotal));
	        bill.setOdd(odd+"");
	        bill.setTotal(total2);
	        bill.setDebt(total2);
	        bill.setSource("货款");
	        bill.setTime(simpleDateFormat.parse(time));
	        bill.setRemark("程序自动填入：制单时实收金额记录");
	        bill.setSaisie(saisie);
	        bill.setAnq(anq);
	        bill.setPhone(phone);
	        bill.setName(name2);
	        bill.setStatus(1);
			billService.save(bill);
		}
		if(OddService.save(oddEntity)){
			return "成功";
		}else
		return "失败";
	}
    @GetMapping("/xinselllist")
    public Object xinselllist(){
        return XinsellService.list();
    }
    @GetMapping("/oddlist")
    public Object oddlist(){
        Map<String, Object> map = new HashMap<>();
        List<Odd> odd=OddService.list(new QueryWrapper<Odd>().eq("status", 1));
        map.put("list", odd);
        double sum=0.00;
        for (int i = 0; i < odd.size(); i++) {
        	sum+=odd.get(i).getTotal();
		}
        map.put("sum", sum);
        return map;
    }
    @GetMapping("/oddlistall")
    public Object oddlistall(){
        Map<String, Object> map = new HashMap<>();
        List<Odd> odd=OddService.list();
        map.put("list", odd);
        double sum=0.00;
        for (int i = 0; i < odd.size(); i++) {
        	sum+=odd.get(i).getTotal();
		}
        map.put("sum", sum);
        return map;
    }
    @GetMapping("/selexinsellbyodd")
    public Object selexinsellbyodd(String odd){
        return XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", odd));
    }
    @GetMapping("/seleoddbyid")
    public Object seleoddbyid(String id){
        Map<String, Object> map = new HashMap<>();
    	Integer idint = Integer.parseInt(id);
    	Odd odd=OddService.getById(idint);
    	map.put("odd", odd);
    	map.put("xinsell", XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", odd.getOdd())));
        return map;
    }
    @GetMapping("/sellsearch")
    public Object sellsearch(String talk,String search){
        Map<String, Object> map = new HashMap<>();
        List<Odd> odd=OddService.list(new QueryWrapper<Odd>().like(Idname.getname(search), talk));
        map.put("list", odd);
        double sum=0.00;
        for (int i = 0; i < odd.size(); i++) {
        	sum+=odd.get(i).getTotal();
		}
        map.put("sum", sum);
        return map;
    }
    @RequestMapping("/seleoddalltime")
    public Map<String, Object> seleoddalltime() throws ParseException{
		Map<String, Object> map = new HashMap<>();
		List<String> yjodd=new ArrayList<>();
		List<String> yj=new ArrayList<>();//预警       存放这个"单号："+odd.get(i).getOdd()+"已逾期"+days+"天"
		List<Odd> odd=OddService.list(new QueryWrapper<Odd>().eq("status", 1));
    	List<String> href=new ArrayList<String>();
		String strodd="";
		for (int i = 0; i < odd.size(); i++) {
			yjodd.add(odd.get(i).getOdd()+"");
			long time=System.currentTimeMillis()-odd.get(i).getTime2().getTime();
//			System.out.println("**********************"+System.currentTimeMillis());
//			System.out.println("**********************"+dateToStamp(odd.get(i).getTime2()));
			long days = (time)/(1000 * 60 * 60 * 24);
			if(days>0&&strodd!=odd.get(i).getOdd()+""&&odd.get(i).getDebt()!=0.00){
				yj.add("单号："+odd.get(i).getOdd()+"已逾期"+days+"天");
				href.add("syso.html?"+odd.get(i).getOdd());
			}
			strodd=odd.get(i).getOdd()+"";//去重
		}
		map.put("count", yj.size());
		map.put("odd", yjodd);
		map.put("str", yj);
        map.put("href",href);
		return map;
	}
    @GetMapping("/oddmax")
    public Integer oddmax(){
    	if(OddService.list().size()==0)return 100001;
    	
    	return OddService.oddmax();
	}
    /* 
     * 将时间转换为时间戳
     */    
    public long dateToStamp(Date date) throws ParseException{
        String res;
        long ts = date.getTime();
//        res = String.valueOf(ts);
//        return res;
        return ts;
    }
    private static void timeuuid(Random random,Calendar now) {//时间戳随机数
    	SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");

		int iii=now.get(Calendar.SECOND);//获取现在的秒
		int iiii=1169988+iii;
		int sum =iiii*1000;//后三位
		
	     System.out.println(sum+random.nextInt(1000));
	}
  //xinsell移除后，型号数量返还
  	public void removeRepertoryinfo(List<Xinsell> sellre) {
  		Map<String, Integer> mapre = new HashMap<>();
  		//统计到mapre
  		for (int i = 0; i < sellre.size(); i++) {
  			if(!mapre.containsKey(sellre.get(i).getModele())){
  				mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite());
  			}else{
  				int numre=mapre.get(sellre.get(i).getModele());
  				mapre.remove(sellre.get(i).getModele());
  				mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite()+numre);
  			}
  		}
  		for (String s : mapre.keySet()) {
  			if(repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).size()==0){
  				RepertoryXH RepertoryXH=repertoryXHService.list(new QueryWrapper<RepertoryXH>().eq("modele", s)).get(0);
  				RepertoryNum RepertoryNum =new RepertoryNum();
  				RepertoryNum.setModele(RepertoryXH.getModele());
  				RepertoryNum.setWall(RepertoryXH.getWall());
  				RepertoryNum.setWeight(RepertoryXH.getWeight());
  				RepertoryNum.setNum(mapre.get(s));
  				RepertoryNum.setQuantite(mapre.get(s));
  				repertoryNumService.save(RepertoryNum);
  				
  				Repertory Repertory=new Repertory();
  				Repertory.setModele(RepertoryXH.getModele());
  				Repertory.setWall(RepertoryXH.getWall());
  				Repertory.setWeight(RepertoryXH.getWeight());
  				Repertory.setNum(mapre.get(s));
  				Repertory.setQuantite(mapre.get(s));
//  				SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//  				String time = sdFormatter.format(new Date());
  				Repertory.setTime(new Date());
  				Repertory.setSaisie("程序生成:货单删除废弃时返还的货物");
  				repertoryService.save(Repertory);
  			}else{
  				RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
  				RepertoryNum.setNum(RepertoryNum.getNum()+mapre.get(s));
  				repertoryNumService.updateById(RepertoryNum);
  			}
  		}
  	}
    //货单启用和废弃
    @RequestMapping("/checkstatus")
    public Object checkStatus(String odd,String status){
    	Integer statusint = Integer.parseInt(status);
        Odd oddentity=OddService.list(new QueryWrapper<Odd>().eq("odd", odd)).get(0);
        List<Xinsell> xinsell=XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", oddentity.getOdd()));

        if(statusint==1){//返还增加
    		List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", odd));
    		for (int i = 0; i < billlist.size(); i++) {
    			Bill billpo=billlist.get(i);
    			billpo.setStatus(0);
    			billService.updateById(billpo);
			}
    		removeRepertoryinfo(xinsell);
    		statusint=0;
        }
        if(statusint==0){//减少
        	Map<String, Integer> mapre = new HashMap<>();
    		//统计到mapre
    		for (int i = 0; i < xinsell.size(); i++) {
    			if(!mapre.containsKey(xinsell.get(i).getModele())){
    				mapre.put(xinsell.get(i).getModele(), xinsell.get(i).getQuantite());
    			}else{
    				int numre=mapre.get(xinsell.get(i).getModele());
    				mapre.remove(xinsell.get(i).getModele());
    				mapre.put(xinsell.get(i).getModele(), xinsell.get(i).getQuantite()+numre);
    			}
    		}
    		for (String s : mapre.keySet()) {
    			RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
    			RepertoryNum.setNum(RepertoryNum.getNum()-mapre.get(s));
    			if(RepertoryNum.getNum()<0){
    				return "库存不足无法启用："+RepertoryNum.getModele();
    			}
    			repertoryNumService.updateById(RepertoryNum);
    		}
    		List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", odd));
    		for (int i = 0; i < billlist.size(); i++) {
    			Bill billpo=billlist.get(i);
    			billpo.setStatus(1);
    			billService.updateById(billpo);
			}
    		statusint=1;
        }
        
        
        
        
        oddentity.setStatus(statusint);
        OddService.updateById(oddentity);
        for (int i = 0; i < xinsell.size(); i++) {
        	Xinsell xinsellentity=xinsell.get(i);
        	xinsellentity.setStatus(statusint);
        	XinsellService.updateById(xinsellentity);
		}
        
        return "";
    }
	@RequestMapping("/deleoddbyid")
    public String deleoddbyid(int id){
    	System.out.println(id+"******************");
    	List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", OddService.getById(id).getOdd()+""));
		List<Xinsell> xinsell=XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", OddService.getById(id).getOdd()+""));
		if(OddService.removeById(id)){
    		for (int i = 0; i < xinsell.size(); i++) {
    			XinsellService.removeById(xinsell.get(i).getId());//删除所属所有货物
			}
    		removeRepertoryinfo(xinsell);
    		

    		for (int i = 0; i < billlist.size(); i++) {
    			billService.removeById(billlist.get(i).getId());
			}
    		
    		return "成功！";
    	}
    	else
    		return "失败！";
    }

    @RequestMapping("/seleprintstatus")
    public Object seleprintstatus(Integer id){ 
    	Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list(new QueryWrapper<Odd>().eq("printstatus", 0).eq("status", 1));
    	List<String> s=new ArrayList<String>();
    	List<String> href=new ArrayList<String>();
    	for (int i = 0; i < a.size(); i++) {
			s.add("单号:"+a.get(i).getOdd());
			href.add("syso.html?"+a.get(i).getOdd());
		}
        map.put("string",s);
        map.put("href",href);
        map.put("data",OddService.list());
        map.put("count",a.size());
    	map.put("code",0);
        map.put("msg"," ");
    return map;
    }
}
